package com.shimao.celnet.payment.ds;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = PaymentDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "paymentSqlSessionFactory")
public class PaymentDataSourceConfig {

    // 精确到 payment db 目录，以便跟其他数据源隔离
    static final String PACKAGE = "com.shimao.celnet.payment.mapperr";
    static final String MAPPER_LOCATION = "classpath:mapper/*.xml";

    @Value("${paymentDB.datasource.url}")
    private String url;

    @Value("${paymentDB.datasource.username}")
    private String user;

    @Value("${paymentDB.datasource.password}")
    private String password;

    @Value("${paymentDB.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "paymentDataSource")
    public DataSource paymentDataSource() {
        DruidDataSource paymentDataSource = new DruidDataSource();
        paymentDataSource.setDriverClassName(driverClass);
        paymentDataSource.setUrl(url);
        paymentDataSource.setUsername(user);
        paymentDataSource.setPassword(password);
        return paymentDataSource;
    }

    @Bean(name = "paymentTransactionManager")
    public DataSourceTransactionManager paymentTransactionManager() {
        return new DataSourceTransactionManager(paymentDataSource());
    }

    @Bean(name = "paymentSqlSessionFactory")
    public SqlSessionFactory paymentSqlSessionFactory(@Qualifier("paymentDataSource") DataSource paymentDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(paymentDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(PaymentDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}